package com.mou.aspect;

import com.mou.context.BaseContext;
import com.mou.entity.OperationLog;
import com.mou.mapper.OperationLogMapper;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Aspect
@Component
public class OperationLogAspect {

    @Autowired
    private OperationLogMapper operationLogMapper;

    @Around("@annotation(com.mou.annotation.Log)")
    @Transactional
    public Object logOperation(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {

        Object result = proceedingJoinPoint.proceed();

        // 获取 HttpServletRequest 实例
        HttpServletRequest request = (HttpServletRequest) ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ipAddress = request.getHeader("X-Forwarded-For");

        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }


        OperationLog operationLog = new OperationLog();
        operationLog.setId(BaseContext.getCurrentId());
        operationLog.setUserId(BaseContext.getCurrentId());
        operationLog.setOperatingTime(LocalDateTime.now());
        operationLog.setClassName(proceedingJoinPoint.getTarget().getClass().getName());
        operationLog.setMethodName(proceedingJoinPoint.getSignature().getName());
        operationLog.setParams(Arrays.toString(proceedingJoinPoint.getArgs()));
        operationLog.setReturnValue(result!=null?result.toString():"void");
        operationLog.setIpAddress(ipAddress);


        log.info("操作日志：{}",operationLog);
        operationLogMapper.insert(operationLog);
        return result;
    }
}
